<?php
namespace app\api\model;
use think\Db;
use app\common\model\Order as OrderModel;
use app\common\exception\BaseException;
use app\common\library\helper;

/**
 * 订单模型
 */
class Order extends OrderModel
{
    /**
     * 隐藏字段
     */
    protected $hidden = [
        'wxapp_id',
        'update_time'
    ];
	
    /**
     * 订单确认-购物车结算
     */
    public function getCart($user,$food_mode,$shop_id,$location)
    {
        $model = new Cart($user['user_id'],$shop_id);
        return $model->getList($user,$food_mode,$location);
    }

    /**
     * 新增订单
     */
    public function add($user_id, $order,$shop_id,$food_mode,$people=0,$ware_price=0,$message,$flavor)
    {
		//如果是打包自取
		$arrive_time = 0;
		if($food_mode==2){
			$arrive_time = $order['arrive_time'];
		}
		//如果是外卖
		if($food_mode==3){
			if (empty($order['address'])) {
				$this->error = '请先选择收货地址';
				return false;
			}
			//计算是否在配送范围
			if(empty($order['address']['location'])){
				$this->error = '请重新完善收货地址';
				return false;
			}
			$shop = Shop::detail($shop_id);
			$result = getDistance($order['address']['location'],$shop['coordinate']);
			if($result){
				$distance = $result[0]['distance'];//获取距离计算结果
				$delivery =Setting::getItem('delivery');//获取派送设置
				if($delivery['delivery_range'] < $distance){
					$this->error = '您已超出派送范围';
					return false;
				}
				
			}else{
				$this->error = '位置计算失败，请重新编辑收货地址';
				return false;
			}
		}
		$pay_price = $order['order_pay_price'];	//实付金额
		//如果是店内 - 计算餐具调料费
		if($food_mode>10000 AND $ware_price>0){
			$pay_price = $pay_price + $ware_price; //加上餐具调料费
		}
        Db::startTrans();
        // 记录订单信息
        $this->save([
            'user_id' => $user_id,
            'wxapp_id' => self::$wxapp_id,
            'order_no' => orderNo(),
            'total_price' => $order['order_total_price'],
			'activity_price' => $order['activity_price'],
            'pay_price' => helper::number2($pay_price),
            'express_price' => $order['express_price'],
			'pack_price' => $order['pack_price'],
			'ware_price' => helper::number2($ware_price),
			'arrive_time' => $arrive_time,
			'table_id' => $food_mode,
			'shop_id' => $shop_id,
			'people' => $people,
			'flavor' => $flavor,
			'message' => $message
        ]);
        // 订单商品列表
        $goodsList = [];
        // 更新商品库存 (下单减库存)
        $deductStockData = [];
        foreach ($order['goods_list'] as $goods) {
            /* @var Goods $goods */
			if($food_mode==3){
				//如果是外卖
				$goods_price = $goods['goods_sku']['out_price'];
			}else{
				$goods_price = $goods['goods_sku']['goods_price'];
			}
            $goodsList[] = [
                'user_id' => $user_id,
                'wxapp_id' => self::$wxapp_id,
                'goods_id' => $goods['goods_id'],
                'goods_name' => $goods['goods_name'],
                'image_id' => $goods['image'][0]['image_id'],
                'deduct_stock_type' => $goods['deduct_stock_type'],
                'spec_type' => $goods['spec_type'],
                'spec_sku_id' => $goods['goods_sku']['spec_sku_id'],
                'goods_spec_id' => $goods['goods_sku']['goods_spec_id'],
                'goods_attr' => $goods['goods_sku']['goods_attr'],
                'content' => $goods['content'],
                'goods_no' => $goods['goods_sku']['goods_no'],
                'goods_price' => $goods_price,
                'line_price' => $goods['goods_sku']['line_price'],
                'total_num' => $goods['total_num'],
                'total_price' => $goods['total_price'],
            ];
            // 下单减库存
            $goods['deduct_stock_type'] == 10 && $deductStockData[] = [
                'goods_spec_id' => $goods['goods_sku']['goods_spec_id'],
                'stock_num' => ['dec', $goods['total_num']]
            ];
        }
        // 保存订单商品信息
        $this->goods()->saveAll($goodsList);
        // 更新商品库存
        !empty($deductStockData) && (new GoodsSpec)->isUpdate()->saveAll($deductStockData);
		//如果是外卖,记录收货地址
		if($food_mode==3){
			$this->address()->save([
				'user_id' => $user_id,
				'wxapp_id' => self::$wxapp_id,
				'name' => $order['address']['name'],
				'phone' => $order['address']['phone'],
				'location' => $order['address']['location'],
				'province' => $order['address']['province'],
				'city' => $order['address']['city'],
				'district' => $order['address']['district'],
				'detail' => $order['address']['detail'],
			]);
		}
        Db::commit();
        return true;
    }

    /**
     * 用户中心订单列表
     */
	public function getList($user_id, $type = '0')
    {
        // 筛选条件
        $filter = [];
		$where = [];
		$filter['user_id'] = $user_id;
		$filter['order_status'] = ['<>',20];
        // 订单数据类型
        switch ($type) {
            case '0':
                break;
            case '10001';
                $filter['table_id'] = ['>',10000];
				$where['table_id'] = 1;
                break;
			case '2';
                $filter['table_id'] = 2;
                break;
            case '3';
                $filter['table_id'] = 3;
                break;
        }
        return $this->with(['goods.image','shop','table'])
            ->where($filter)
			->whereOr($where)
            ->order(['create_time' => 'desc'])
            ->select();
    }
	
	
	/**
     * 开始配送
     */
    public function receipt_star()
    {
        if ($this['pay_status']['value'] == 10
            || $this['delivery_status']['value'] == 10) {
            $this->error = '该订单不合法';
            return false;
        }
        return $this->save([
            'receipt_status' => 20,
            'receipt_time' => time(),
        ]);
    }
	
	/**
     * 配送完成
     */
    public function receipt_end()
    {
        if ($this['pay_status']['value'] == 10
            || $this['delivery_status']['value'] == 10) {
            $this->error = '该订单不合法';
            return false;
        }
        return $this->save([
            'receipt_status' => 30,
            'receipt_time' => time(),
        ]);
    }

    /**
     * 取消订单
     */
    public function cancel()
    {
        if ($this['pay_status']['value'] == 20) {
            $this->error = '已付款订单不可取消';
            return false;
        }
        // 回退商品库存
        $this->backGoodsStock($this['goods']);
        return $this->save(['order_status' => 20]);
    }

    /**
     * 回退商品库存
     */
    private function backGoodsStock(&$goodsList)
    {
        $goodsSpecSave = [];
        foreach ($goodsList as $goods) {
            // 下单减库存
            if ($goods['deduct_stock_type'] == 10) {
                $goodsSpecSave[] = [
                    'goods_spec_id' => $goods['goods_spec_id'],
                    'stock_num' => ['inc', $goods['total_num']]
                ];
            }
        }
        // 更新商品规格库存
        return !empty($goodsSpecSave) && (new GoodsSpec)->isUpdate()->saveAll($goodsSpecSave);
    }

    /**
     * 确认收货
     */
	public function receipt()
    {
        if ($this['delivery_status']['value'] == 10) {
            $this->error = '该订单不合法';
            return false;
        }
		post_tpl('finish',$this->order_id);
        return $this->save([
            'receipt_status' => 30,
            'receipt_time' => time(),
            'order_status' => 30
        ]);
    }
	

    /**
     * 获取订单总数
     */
	public function getApiCount($user_id, $type = '0')
    {
        // 筛选条件
        $filter = [];
		$where = [];
		$filter['user_id'] = $user_id;
		$filter['order_status'] = 10;
        // 订单数据类型
        switch ($type) {
            case '0':
                break;
            case '10001';
                $filter['table_id'] = ['>',10000];
				$where['table_id'] = 1;
                break;
			case '2';
                $filter['table_id'] = 2;
                break;
            case '3';
                $filter['table_id'] = 3;
                break;
        }
        return $this->where($filter)
			->whereOr($where)
            ->count();
    }
	

    /**
     * 订单详情
     */
    public static function getUserOrderDetail($order_id, $user_id)
    {
        if (!$order = self::get([
            'order_id' => $order_id,
            'user_id' => $user_id,
            'order_status' => ['<>', 20]
        ], ['goods' => ['image', 'spec', 'goods'], 'address', 'shop', 'table','clerk'])) {
            throw new BaseException(['msg' => '订单不存在']);
        }
        return $order;
    }

    /**
     * 判断商品库存不足 (未付款订单)
     */
    public function checkGoodsStatusFromOrder(&$goodsList)
    {
        foreach ($goodsList as $goods) {
            // 判断商品是否下架
            if ($goods['goods']['goods_status']['value'] != 10) {
                $this->setError('很抱歉，商品 [' . $goods['goods_name'] . '] 已下架');
                return false;
            }
            // 付款减库存
            if ($goods['deduct_stock_type'] == 20 && $goods['spec']['stock_num'] < 1) {
                $this->setError('很抱歉，商品 [' . $goods['goods_name'] . '] 库存不足');
                return false;
            }
        }
        return true;
    }

    /**
     * 设置错误信息
     */
    private function setError($error)
    {
        empty($this->error) && $this->error = $error;
    }

    /**
     * 是否存在错误
     */
    public function hasError()
    {
        return !empty($this->error);
    }
}
